package com.macro.mall.interceptor;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.util.Properties;


@Component
@Intercepts({@Signature(
        type = StatementHandler.class,
        method = "prepare",
        args = {Connection.class, Integer.class}
)})
public class UpdateInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        String originalSql = statementHandler.getBoundSql().getSql();
        if (isDelete(originalSql)) {
            throw new RuntimeException("删除操作被阻止,请联系管理员或用逻辑删除");

        } else if (isFullTableUpdate(originalSql)) {
            throw new RuntimeException("全表更新操作被阻止");
        }
        return invocation.proceed();
    }

    private boolean isFullTableUpdate(String sql) {
        // 简单的检查逻辑，例如检查是否包含UPDATE而没有WHERE子句
        return (sql.toUpperCase().startsWith("UPDATE")) && !sql.toUpperCase().contains(" WHERE ");
    }

    private boolean isDelete(String sql) {
        // 简单的检查逻辑，例如检查是否包含UPDATE而没有WHERE子句
        return sql.toUpperCase().startsWith("DELETE");
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 可以从配置文件中读取额外的属性
    }
}